import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/login")
public class Login extends HttpServlet {
    //登录服务
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置请求和响应的格式
        req.setCharacterEncoding("utf8");
        resp.setContentType("text/html; charset=utf8");
        //获取用户名和密码
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        if(username == null || username.equals("") || password == null || password.equals("")) {
            resp.setStatus(403);
            resp.getWriter().write("用户名或密码不能为空!");
            return;
        }
        //根据username获取user数据
        UserDao userDao = new UserDao();
        User user = userDao.selectByName(username);
        if (user == null) {
            resp.setStatus(403);
            resp.getWriter().write("该用户名不存在!");
            return;
        }
        //检测密码是否正确
        if(!password.equals(user.getPassword())) {
            resp.setStatus(403);
            resp.getWriter().write("用户名或密码错误!");
            return;
        }
        //创建会话
        HttpSession session = req.getSession();
        session.setAttribute("user", user);
        //重定向到博客列表页
        resp.sendRedirect("blog_list.html");
    }

    //检测登录
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取当前会话
        HttpSession session = req.getSession();
        if(session == null) {
            //返回错误状态即可
            resp.setStatus(403);
            return;
        }
        //获取user信息(是否登录主要看他：注销登录是通过删除user信息实现的)
        User user = (User) session.getAttribute("user");
        if(user == null) {
            //返回错误状态即可
            resp.setStatus(403);
            return;
        }
        //成功了就什么都不用干
        resp.setStatus(200);
    }
}
